<template>
	<view class="userLayout">
		<view class="userInfo">
			<view class="avatar">
				<image :src="userInfo.avatar || '/src/static/logo.png'" mode="aspectFill"></image>
			</view>
			<view class="name">{{ userInfo.nickName || '暂无昵称' }}</view>
			<view class="email" v-if="userInfo.email">{{ userInfo.email }}</view>
		</view>
		
		<view class="section">
			<view class="list">
				<view class="row" @tap="editProfile">
					<view class="left">
						<uni-icons type="person-filled" size="20" color="#1296db"></uni-icons>
						<view class="text">编辑资料</view>
					</view>
					<view class="right">
						<uni-icons type="right" size="20" color="#2c2c2c"></uni-icons>
					</view>
				</view>
				<view class="row" @tap="changePassword">
					<view class="left">
						<uni-icons type="locked-filled" size="20" color="#1296db"></uni-icons>
						<view class="text">修改密码</view>
					</view>
					<view class="right">
						<uni-icons type="right" size="20" color="#2c2c2c"></uni-icons>
					</view>
				</view>
			</view>
		</view>
		
		<view class="section">
			<view class="list">
				<view class="row" @tap="handleAuth" v-if="!hasToken">
					<view class="left">
						<uni-icons type="person-filled" size="20" color="#1296db"></uni-icons>
						<view class="text">去登录</view>
					</view>
					<view class="right">
						<uni-icons type="right" size="20" color="#2c2c2c"></uni-icons>
					</view>
				</view>
				<view class="row" @tap="handleLogout" v-else>
					<view class="left">
						<uni-icons type="logout" size="20" color="#ff4757"></uni-icons>
						<view class="text">退出登录</view>
					</view>
					<view class="right">
						<uni-icons type="right" size="20" color="#2c2c2c"></uni-icons>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { getUserInfo, logout, updateUserInfo, changePassword as changeUserPassword } from '@/api'

const userInfo = ref({})

// 计算是否有token
const hasToken = computed(() => {
  return !!uni.getStorageSync('accessToken')
})

// 获取用户信息
const loadUserInfo = async () => {
  try {
    // 检查是否有token
    const token = uni.getStorageSync('accessToken')
    if (!token) {
      // 没有token，显示未登录状态
      userInfo.value = { nickName: '请登录' }
      return
    }
    
    // 先从本地存储获取用户信息
    const localUserInfo = uni.getStorageSync('userInfo')
    if (localUserInfo) {
      userInfo.value = localUserInfo
    }
    
    // 再从服务器获取最新用户信息
    const serverUserInfo = await getUserInfo()
    // 处理嵌套的profile数据结构
    const profile = serverUserInfo.profile || {}
    const processedUserInfo = {
      id: serverUserInfo.id,
      username: serverUserInfo.username,
      nickName: profile.nickName,
      gender: profile.gender ?? 0,  // 处理null值
      email: profile.email,
      address: profile.address,
      // 处理avatar字段，去掉多余的引号
      avatar: profile.avatar ? profile.avatar.replace(/^'|'$/g, '') : null
    }
    userInfo.value = processedUserInfo
    
    // 更新本地存储
    uni.setStorageSync('userInfo', processedUserInfo)
  } catch (error) {
    console.error('获取用户信息失败:', error)
    // 如果获取失败但有token，可能是网络问题，保持本地数据
    const localUserInfo = uni.getStorageSync('userInfo')
    if (localUserInfo) {
      userInfo.value = localUserInfo
    } else {
      userInfo.value = { nickName: '网络错误' }
    }
  }
}

// 编辑资料
const editProfile = () => {
  const token = uni.getStorageSync('accessToken')
  if (!token) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    })
    return
  }
  
  refreshFlag.value = true  // 设置刷新标志
  // 跳转到编辑资料页面
  uni.navigateTo({
    url: '/pages/user/editProfile'
  })
}

// 修改密码
const changePassword = () => {
  const token = uni.getStorageSync('accessToken')
  if (!token) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    })
    return
  }
  
  // 跳转到修改密码页面
  uni.navigateTo({
    url: '/pages/user/changePassword'
  })
}

// 处理登录
const handleAuth = () => {
  uni.navigateTo({
    url: '/pages/login/login'
  })
}

// 退出登录
const handleLogout = async () => {
  uni.showModal({
    title: '提示',
    content: '确定要退出登录吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          // 调用登出API
          await logout()
          
          // 清除本地存储
          uni.removeStorageSync('accessToken')
          uni.removeStorageSync('refreshToken')
          uni.removeStorageSync('userInfo')
          
          // 跳转到登录页
          uni.reLaunch({
            url: '/pages/login/login'
          })
          
          uni.showToast({
            title: '已退出登录',
            icon: 'success'
          })
        } catch (error) {
          console.error('退出登录失败:', error)
          // 即使API调用失败，也清除本地数据
          uni.removeStorageSync('accessToken')
          uni.removeStorageSync('refreshToken')
          uni.removeStorageSync('userInfo')
          uni.reLaunch({
            url: '/pages/login/login'
          })
        }
      }
    }
  })
}

// 页面首次加载
onMounted(() => {
  loadUserInfo()
  
  // 监听刷新用户信息事件
  uni.$on('refreshUserInfo', () => {
    loadUserInfo()
  })
})

// 页面卸载时移除事件监听
onUnmounted(() => {
  uni.$off('refreshUserInfo')
})

// 添加页面显示时的刷新逻辑
const refreshFlag = ref(false)


</script>

<style lang="scss" scoped>
	.userLayout{
		.userInfo{
			display: flex;
			align-items: center;
			justify-content: center;
			flex-direction: column;
			padding: 50rpx 0;
			.avatar{
				width: 160rpx;
				height: 160rpx;
				border-radius: 50%;
				overflow: hidden;
				image{
					width: 100%;
					height: 100%;
				}
			}
		}
		.section{
			width: 690rpx;
			margin: 50rpx auto;
			border: 1px solid #eee;
			border-radius: 10rpx;
			box-shadow: 0 0 30rpx rgba(0,0,0,0.05);
			.list{
				.row{
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 0 30rpx;
					height: 100rpx;
					border-bottom: 1px solid #eee;
					&:last-child{border-bottom: 0}
					.left{
						display: flex;
						align-items: center;
						.text{
							padding-left: 20rpx;
							color: #2c2c2c;
						}
					}
					.right{
						display: flex;
						align-items: center;
					}
				}
			}
		}
	}
	
	.name {
		font-size: 36rpx;
		font-weight: 600;
		color: #2c2c2c;
		margin-bottom: 10rpx;
	}
	
	.email {
		font-size: 28rpx;
		color: #666;
	}
</style>
